package com.cms.authority.interceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.util.WebUtils;

import com.cms.common.kit.Constant;
import com.cms.common.kit.URLKit;
import com.cms.common.util.pass.SystemDecoder;
import com.cms.model.Admin;

/**
 * 后台管理员登录过滤器。
 * 
 * @author life
 * 
 */
public class AdminLoginInteceptor implements HandlerInterceptor {

	private final static Logger logger = Logger.getLogger(AdminLoginInteceptor.class);


	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		/**
		 * 共用方法
		 */
		request.setAttribute("now_time", System.currentTimeMillis());
		request.setAttribute("baseUrl", URLKit.getBaseUrl(request));
		request.setAttribute("currentUrl", URLKit.getPageUrl(request));
		
		String requestUrl = request.getRequestURL().toString();
		//检查是否需要过滤
		if(URLKit.checkUrl(requestUrl)){
			Cookie cookie = WebUtils.getCookie(request, Constant.CURRENT_ADMIN_COOKIE_INFO);
			if(cookie!=null){
				//存在cookie
				String admin_id = cookie.getValue();
				admin_id=SystemDecoder._Decrypt(admin_id);
				Admin admin = Admin.dao.findById(admin_id);
				if(admin!=null){
					return true;
				}
			}
			response.sendRedirect(request.getContextPath() +"/admin/toLogin");
			return false;
		}
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
	}

	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
	}

}
